<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::section})}">

<head>
    <title>我的借阅 - 图书馆管理系统</title>
</head>

<body>
    <section>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>我的借阅</h2>
            <a href="/book/list" class="btn btn-primary">
                <i class="fas fa-book"></i> 去借阅图书
            </a>
        </div>

        <!-- 借阅统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title">总借阅数</h6>
                                <h2 id="totalBorrowCount">0</h2>
                            </div>
                            <i class="fas fa-book-reader fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title">当前借阅</h6>
                                <h2 id="currentBorrowCount">0</h2>
                            </div>
                            <i class="fas fa-book fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title">即将到期</h6>
                                <h2 id="soonDueCount">0</h2>
                            </div>
                            <i class="fas fa-clock fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title">已逾期</h6>
                                <h2 id="overdueCount">0</h2>
                            </div>
                            <i class="fas fa-exclamation-circle fa-3x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 借阅记录标签页 -->
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="borrowTabs" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="current-tab" data-toggle="tab" href="#current" role="tab">
                            当前借阅
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="history-tab" data-toggle="tab" href="#history" role="tab">
                            借阅历史
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="overdue-tab" data-toggle="tab" href="#overdue" role="tab">
                            逾期记录
                        </a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="borrowTabContent">
                    <!-- 当前借阅 -->
                    <div class="tab-pane fade show active" id="current" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>图书名称</th>
                                        <th>借阅时间</th>
                                        <th>预计归还时间</th>
                                        <th>剩余天数</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="currentBorrowList">
                                    <!-- 当前借阅数据将通过AJAX加载 -->
                                    <tr>
                                        <td colspan="5" class="text-center">
                                            <div class="spinner-border text-primary" role="status">
                                                <span class="sr-only">Loading...</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- 借阅历史 -->
                    <div class="tab-pane fade" id="history" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>图书名称</th>
                                        <th>借阅时间</th>
                                        <th>归还时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="historyBorrowList">
                                    <!-- 借阅历史数据将通过AJAX加载 -->
                                    <tr>
                                        <td colspan="5" class="text-center">
                                            <div class="spinner-border text-primary" role="status">
                                                <span class="sr-only">Loading...</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- 逾期记录 -->
                    <div class="tab-pane fade" id="overdue" role="tabpanel">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>图书名称</th>
                                        <th>借阅时间</th>
                                        <th>应还时间</th>
                                        <th>归还时间</th>
                                        <th>逾期天数</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody id="overdueBorrowList">
                                    <!-- 逾期记录数据将通过AJAX加载 -->
                                    <tr>
                                        <td colspan="6" class="text-center">
                                            <div class="spinner-border text-primary" role="status">
                                                <span class="sr-only">Loading...</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图书详情模态框 -->
        <div class="modal fade" id="bookDetailModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="bookDetailTitle">图书详情</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-4">
                                <img id="bookCover" src="/images/book-cover-placeholder.jpg" alt="Book Cover"
                                    class="img-fluid rounded mb-3">
                            </div>
                            <div class="col-md-8">
                                <h4 id="bookName">图书名称</h4>
                                <p class="text-muted" id="bookAuthor">作者</p>
                                <div class="mb-3">
                                    <span class="badge badge-primary" id="bookCategory">分类</span>
                                    <span class="badge badge-info" id="bookISBN">ISBN</span>
                                </div>
                                <div class="mb-3">
                                    <label class="font-weight-bold">出版社:</label>
                                    <span id="bookPublisher">出版社</span>
                                </div>
                                <div class="mb-3">
                                    <label class="font-weight-bold">出版日期:</label>
                                    <span id="bookPublishDate">出版日期</span>
                                </div>
                                <div class="mb-3">
                                    <label class="font-weight-bold">评分:</label>
                                    <span class="text-warning" id="bookRating">★★★★☆</span>
                                    <span id="bookRatingValue">4.0</span>
                                </div>
                                <hr>
                                <div class="mb-3">
                                    <label class="font-weight-bold">简介:</label>
                                    <p id="bookDescription">图书简介...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <a href="#" id="bookDetailLink" class="btn btn-primary">查看详情</a>
                    </div>
                </div>
            </div>
        </div>

        <script>
            $(document).ready(function () {
                // 获取当前登录用户信息
                const username = localStorage.getItem('username');
                if (!username) {
                    // 未登录，跳转到登录页面
                    window.location.href = '/login';
                    return;
                }

                // 加载借阅统计
                loadBorrowStats(username);

                // 加载当前借阅
                loadCurrentBorrows(username);

                // 标签页切换事件
                $('#borrowTabs a').on('click', function (e) {
                    e.preventDefault();
                    $(this).tab('show');

                    const tabId = $(this).attr('href');
                    if (tabId === '#history' && $('#historyBorrowList .spinner-border').length > 0) {
                        loadHistoryBorrows(username);
                    } else if (tabId === '#overdue' && $('#overdueBorrowList .spinner-border').length > 0) {
                        loadOverdueBorrows(username);
                    }
                });
            });

            // 加载借阅统计
            function loadBorrowStats(username) {
                const userId = localStorage.getItem('userId'); // 获取用户ID
                console.log("loadBorrowStats - 获取到的用户ID: ", userId);
                if (!userId) {
                    console.error("用户ID未找到，无法加载借阅统计。");
                    return;
                }

                $.ajax({
                    url: '/borrow/api/statistics/' + userId,
                    type: 'GET',
                    success: function (res) {
                        if (res.code === 200 && res.data) {
                            const stats = res.data;
                            $('#totalBorrowCount').text(stats.totalBorrowCount);
                            $('#currentBorrowCount').text(stats.currentBorrowCount);
                            $('#soonDueCount').text(stats.soonDueCount);
                            $('#overdueCount').text(stats.overdueCount);
                        } else {
                            console.error('加载借阅统计失败:', res.message);
                            alert('加载借阅统计失败: ' + res.message);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，加载借阅统计失败:', textStatus, errorThrown, jqXHR);
                        alert('服务器错误，加载借阅统计失败！');
                    }
                });
            }

            // 加载当前借阅
            function loadCurrentBorrows(username) {
                const userId = localStorage.getItem('userId'); // 获取用户ID
                console.log("loadCurrentBorrows - 获取到的用户ID: ", userId);
                if (!userId) {
                    console.error("用户ID未找到，无法加载当前借阅记录。");
                    return;
                }
                $('#currentBorrowList').html('<tr><td colspan="5" class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></td></tr>');

                $.ajax({
                    url: '/borrow/api/listByUserId/' + userId,
                    type: 'GET',
                    success: function (res) {
                        let html = '';
                        if (res.code === 200 && res.data && res.data.length > 0) {
                            const borrows = res.data.filter(b => b.status === 1); // 过滤出当前借阅中的记录
                            if (borrows.length > 0) {
                                for (let i = 0; i < borrows.length; i++) {
                                    const borrow = borrows[i];
                                    const borrowTime = new Date(borrow.borrowTime).toLocaleDateString();
                                    const expectedReturnTime = new Date(borrow.expectedReturnTime).toLocaleDateString();

                                    // 计算剩余天数
                                    const now = new Date();
                                    const expectedReturnDate = new Date(borrow.expectedReturnTime);
                                    const diffTime = expectedReturnDate.getTime() - now.getTime();
                                    const remainingDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

                                    // 根据剩余天数设置不同的样式
                                    let remainingDaysText = '';
                                    let remainingDaysClass = '';
                                    if (remainingDays <= 0) {
                                        remainingDaysText = '已逾期';
                                        remainingDaysClass = 'text-danger font-weight-bold';
                                    } else if (remainingDays <= 3) {
                                        remainingDaysText = remainingDays + '天';
                                        remainingDaysClass = 'text-warning font-weight-bold';
                                    } else {
                                        remainingDaysText = remainingDays + '天';
                                    }

                                    html += `
                                        <tr>
                                            <td>
                                                <a href="#" onclick="showBookDetail(${borrow.bookId})">
                                                    ${borrow.bookName}
                                                </a>
                                            </td>
                                            <td>${borrowTime}</td>
                                            <td>${expectedReturnTime}</td>
                                            <td class="${remainingDaysClass}">
                                                ${remainingDaysText}
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-success" onclick="renewBook(${borrow.id})">
                                                    <i class="fas fa-sync-alt"></i> 续借
                                                </button>
                                                <button type="button" class="btn btn-sm btn-primary" onclick="returnBook(${borrow.id})">
                                                    <i class="fas fa-undo"></i> 归还
                                                </button>
                                            </td>
                                        </tr>
                                    `;
                                }
                            } else {
                                html = '<tr><td colspan="5" class="text-center">暂无借阅中的记录</td></tr>';
                            }
                        } else {
                            console.error('加载当前借阅记录失败:', res.message);
                            html = '<tr><td colspan="5" class="text-center text-danger">加载借阅记录失败: ' + (res.message || '未知错误') + '</td></tr>';
                        }
                        $('#currentBorrowList').html(html);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，加载当前借阅记录失败:', textStatus, errorThrown, jqXHR);
                        $('#currentBorrowList').html('<tr><td colspan="5" class="text-center text-danger">服务器错误，加载借阅记录失败！</td></tr>');
                    }
                });
            }

            // 加载借阅历史
            function loadHistoryBorrows(username) {
                const userId = localStorage.getItem('userId'); // 获取用户ID
                console.log("loadHistoryBorrows - 获取到的用户ID: ", userId);
                if (!userId) {
                    console.error("用户ID未找到，无法加载借阅历史记录。");
                    return;
                }
                $('#historyBorrowList').html('<tr><td colspan="5" class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></td></tr>');

                $.ajax({
                    url: '/borrow/api/listByUserId/' + userId,
                    type: 'GET',
                    success: function (res) {
                        let html = '';
                        if (res.code === 200 && res.data && res.data.length > 0) {
                            const borrows = res.data.filter(b => b.status === 2 || b.status === 0); // 过滤出已归还或已取消的记录
                            if (borrows.length > 0) {
                                for (let i = 0; i < borrows.length; i++) {
                                    const borrow = borrows[i];
                                    const borrowTime = new Date(borrow.borrowTime).toLocaleDateString();
                                    const returnTime = borrow.actualReturnTime ? new Date(borrow.actualReturnTime).toLocaleDateString() : '-';

                                    let statusText = '';
                                    let statusClass = '';
                                    switch (borrow.status) {
                                        case 0:
                                            statusText = '已取消';
                                            statusClass = 'badge-secondary';
                                            break;
                                        case 2:
                                            statusText = '已归还';
                                            statusClass = 'badge-success';
                                            break;
                                        case 3:
                                            statusText = '已逾期';
                                            statusClass = 'badge-danger';
                                            break;
                                    }

                                    html += `
                                        <tr>
                                            <td>
                                                <a href="#" onclick="showBookDetail(${borrow.bookId})">
                                                    ${borrow.bookName}
                                                </a>
                                            </td>
                                            <td>${borrowTime}</td>
                                            <td>${returnTime}</td>
                                            <td><span class="badge ${statusClass}">${statusText}</span></td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-info" onclick="showBorrowDetail(${borrow.id})">
                                                    <i class="fas fa-eye"></i> 详情
                                                </button>
                                                ${borrow.status === 2 ? `
                                                    <button type="button" class="btn btn-sm btn-primary" onclick="addComment(${borrow.bookId})">
                                                        <i class="fas fa-comment"></i> 评论
                                                    </button>
                                                ` : ''}
                                            </td>
                                        </tr>
                                    `;
                                }
                            } else {
                                html = '<tr><td colspan="5" class="text-center">暂无借阅历史记录</td></tr>';
                            }
                        } else {
                            console.error('加载借阅历史记录失败:', res.message);
                            html = '<tr><td colspan="5" class="text-center text-danger">加载借阅历史记录失败: ' + (res.message || '未知错误') + '</td></tr>';
                        }
                        $('#historyBorrowList').html(html);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，加载借阅历史记录失败:', textStatus, errorThrown, jqXHR);
                        $('#historyBorrowList').html('<tr><td colspan="5" class="text-center text-danger">服务器错误，加载借阅历史记录失败！</td></tr>');
                    }
                });
            }

            // 加载逾期记录
            function loadOverdueBorrows(username) {
                const userId = localStorage.getItem('userId'); // 获取用户ID
                console.log("loadOverdueBorrows - 获取到的用户ID: ", userId);
                if (!userId) {
                    console.error("用户ID未找到，无法加载逾期记录。");
                    return;
                }
                $('#overdueBorrowList').html('<tr><td colspan="5" class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></td></tr>');

                $.ajax({
                    url: '/borrow/api/listByUserId/' + userId,
                    type: 'GET',
                    success: function (res) {
                        let html = '';
                        if (res.code === 200 && res.data && res.data.length > 0) {
                            const borrows = res.data.filter(b => b.status === 3); // 过滤出逾期记录
                            if (borrows.length > 0) {
                                for (let i = 0; i < borrows.length; i++) {
                                    const borrow = borrows[i];
                                    const borrowTime = new Date(borrow.borrowTime).toLocaleDateString();
                                    const expectedReturnTime = new Date(borrow.expectedReturnTime).toLocaleDateString();

                                    html += `
                                        <tr>
                                            <td>
                                                <a href="#" onclick="showBookDetail(${borrow.bookId})">
                                                    ${borrow.bookName}
                                                </a>
                                            </td>
                                            <td>${borrowTime}</td>
                                            <td>${expectedReturnTime}</td>
                                            <td class="text-danger font-weight-bold">已逾期</td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-info" onclick="showBorrowDetail(${borrow.id})">
                                                    <i class="fas fa-eye"></i> 详情
                                                </button>
                                                <button type="button" class="btn btn-sm btn-danger" onclick="addFine(${borrow.id})">
                                                    <i class="fas fa-coins"></i> 罚款
                                                </button>
                                            </td>
                                        </tr>
                                    `;
                                }
                            } else {
                                html = '<tr><td colspan="5" class="text-center">暂无逾期记录</td></tr>';
                            }
                        } else {
                            console.error('加载逾期记录失败:', res.message);
                            html = '<tr><td colspan="5" class="text-center text-danger">加载逾期记录失败: ' + (res.message || '未知错误') + '</td></tr>';
                        }
                        $('#overdueBorrowList').html(html);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，加载逾期记录失败:', textStatus, errorThrown, jqXHR);
                        $('#overdueBorrowList').html('<tr><td colspan="5" class="text-center text-danger">服务器错误，加载逾期记录失败！</td></tr>');
                    }
                });
            }

            // 显示图书详情
            function showBookDetail(bookId) {
                alert('查看图书详情: ' + bookId);
                // 这里可以发送AJAX请求获取图书详情并填充模态框
            }

            // 显示借阅详情
            function showBorrowDetail(borrowId) {
                alert('查看借阅详情: ' + borrowId);
                // 这里可以发送AJAX请求获取借阅详情并填充模态框
            }

            // 添加评论
            function addComment(bookId) {
                alert('添加评论: ' + bookId);
                // 这里可以跳转到评论添加页面或弹出评论模态框
            }

            // 添加罚款
            function addFine(borrowId) {
                alert('添加罚款: ' + borrowId);
                // 这里可以跳转到罚款添加页面或弹出罚款模态框
            }

            // 续借图书
            function renewBook(id) {
                if (confirm('确定要续借这本书吗？')) {
                    alert('续借功能开发中...');
                    // 实际项目中应该发送AJAX请求到后端续借
                }
            }

            // 归还图书
            function returnBook(id) {
                if (confirm('确定要归还这本书吗？')) {
                    $.ajax({
                        url: '/borrow/api/return/' + id,
                        type: 'PUT',
                        success: function (res) {
                            if (res.code === 200) {
                                alert('归还成功！');
                                loadCurrentBorrows(localStorage.getItem('username')); // 重新加载当前借阅列表
                                loadBorrowStats(localStorage.getItem('username')); // 重新加载借阅统计
                                loadHistoryBorrows(localStorage.getItem('username')); // 重新加载借阅历史
                            } else {
                                console.error('归还失败：', res.message);
                                alert('归还失败：' + res.message);
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            console.error('服务器错误，归还失败:', textStatus, errorThrown, jqXHR);
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }
            }
        </script>
    </section>
</body>

</html>